<?php
require_once APPLICATION_PATH . '/forms/Auth/Login.php';  

class AuthController extends Zend_Controller_Action
{
 
    public function init()
    {

        $this->_helper->layout()->setLayout('simple');
     
    }

    public function logoutAction()
    {

        $auth = Zend_Auth::getInstance();
        $auth->clearIdentity();
        $authNamespace = new Zend_Session_Namespace('Zend_Auth');
        $authNamespace->user = null;
        $authNamespace->userRole = null;
        $this->_redirect('/');
    }

    public function loginAction()
    {
        //$db = $this->_getParam('db');
        $db	= Zend_Db_Table_Abstract::getDefaultAdapter();
        $loginForm = new Application_Form_Auth($_POST);
 
        if ($this->getRequest()->isPost()) {
            if ($loginForm->isValid($_POST)) {
     
                $adapter = new Zend_Auth_Adapter_DbTable(
                    $db,
                    'user',
                    'username',
                    'password',
                    'MD5(?)'
                    );
     
                $adapter->setIdentity($loginForm->getValue('username'));
                $adapter->setCredential($loginForm->getValue('password'));

                $auth = Zend_Auth::getInstance();

                $result = $auth->authenticate($adapter);
                if ($result->isValid()) {
                    $identity = $result->getIdentity();
                    
                    
                    $user = new  Application_Model_User();
                    $mapper  = new Application_Model_UserMapper();
                    $user = $mapper->findByUsername($identity, $user);

                    Zend_Session::start();
                    $authNamespace = new Zend_Session_Namespace('Zend_Auth');
                    $authNamespace->user = $user->getUsername();
                    $authNamespace->userRole = $user->getRole();

                    if ($authNamespace->userRole == 'admin') {
                        $this->_redirect('/admin');
                    } else {
                        $this->_redirect('/user-tests/');
                    }
                    return;
                    
                } else {
                    $aux_msgs = $result->getMessages();
                    $this->view->message = $aux_msgs[0];
                }
     
            }
        }
        

        $this->view->loginForm = $loginForm;
        $this->render();
 
    }
 
}

?>